package com.dtagri.fjwlw.fragment;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.ButterKnife;

import com.dtagri.fjwlw.AppContext;
import com.dtagri.fjwlw.R;
import com.dtagri.fjwlw.base.BaseFragment;
import com.dtagri.fjwlw.bean.TjCompanyRegion;
import com.dtagri.fjwlw.broadcastreceiver.TReceiver;
import com.dtagri.fjwlw.ui.LoginActivity;
import com.dtagri.fjwlw.ui.MainActivity;
import com.dtagri.fjwlw.ui.ServerActivity;
import com.dtagri.fjwlw.ui.ZSimpleBackActivity;
import com.dtagri.fjwlw.ui.ZSimpleBackPage;
import com.dtagri.fjwlw.util.FileUtil;
import com.dtagri.fjwlw.util.MethodsCompat;
import com.dtagri.fjwlw.util.TToast;
import com.dtagri.fjwlw.widget.CommonDialog;
import com.dtagri.fjwlw.widget.DialogHelper;

/**
 * （我的）管理中心 
 * @author wxjn
 * 
 */
public class ManageFragment extends BaseFragment {

	private TextView company;
	private TextView basename;
	private RelativeLayout userUnlogin;
	private TextView tvMyLogin;
	private TReceiver tReceiver;
	private ImageView avatar1;
	private LinearLayout rl_server;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.fragment_my_information,
				container, false);
		ButterKnife.inject(this, view);
		initView(view);
		return view;

	}

	@Override
	public void initView(View view) {
		view.findViewById(R.id.rl_about).setOnClickListener(this);
		view.findViewById(R.id.rl_server).setOnClickListener(this);
		view.findViewById(R.id.rl_exit).setOnClickListener(this);
		view.findViewById(R.id.rl_clean_cache).setOnClickListener(this);
		company = (TextView) view.findViewById(R.id.tv_my_company);
		avatar1 = (ImageView) view.findViewById(R.id.iv_avatar1);
		basename = (TextView) view.findViewById(R.id.tv_my_basename);
		userUnlogin = (RelativeLayout) view.findViewById(R.id.rl_user_unlogin);
		rl_server = (LinearLayout)view.findViewById(R.id.rl_server);
		tvMyLogin = (TextView) view.findViewById(R.id.tv_my_login);
		userUnlogin.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (AppContext.isLogin()) {
			company.setText(AppContext.user.getCompanyName());
			avatar1.setImageResource(R.drawable.widget_dface_over);
			TjCompanyRegion tjCompanyRegion = AppContext.user
					.getTjCompanyRegions().get(
							AppContext.userOperate.getCurBaseIndex());
			basename.setText(tjCompanyRegion.getRegionName());
			tvMyLogin.setText("退出登录");
			rl_server.setVisibility(View.GONE);
		} else {
			company.setText("未登录");
			basename.setText("");
			avatar1.setImageResource(R.drawable.widget_dface_nor);
			tvMyLogin.setText("点击登录");
			rl_server.setVisibility(View.VISIBLE);
		}
		tReceiver = new TReceiver(getActivity(), TReceiver.CHANG_BASE) {

			@Override
			public void onReceive(Context arg0, Intent arg1) {
				onResume();
			}
		};
	}

	@Override
	public void onPause() {
		super.onPause();
		tReceiver.unregisterReceiver();
	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		Intent intent;
		switch (id) {
		case R.id.rl_about:
			intent = new Intent(getActivity(), ZSimpleBackActivity.class);
			intent.putExtra(ZSimpleBackActivity.BUNDLE_KEY_PAGE,
					ZSimpleBackPage.ABOUT.getValue());
			startActivity(intent);
			break;
		case R.id.rl_server:
			intent = new Intent(getActivity(), ServerActivity.class);
			startActivity(intent);
			break;
		case R.id.rl_clean_cache:
			onClickCleanCache();
			break;
		case R.id.rl_exit:		//退出
			if (!AppContext.isLogin()) {
				intent = new Intent(getActivity(), LoginActivity.class);
				startActivity(intent);
			} else {
				showConfirmDialog();
			}
			break;
		case R.id.rl_user_unlogin:		//登录
			if (!AppContext.isLogin()) {
				intent = new Intent(getActivity(), LoginActivity.class);
				startActivity(intent);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 是否确认退出
	 */
	private void showConfirmDialog() {
		final CommonDialog dlg = DialogHelper
				.getPinterestDialogCancelable(getActivity());
		dlg.setTitle("警告");
		dlg.setMessage("确定退出登录?");
		dlg.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				rl_server.setVisibility(View.VISIBLE);
				System.out.println(AppContext.user.getServerIp());
				AppContext.cleanLoginInfo(AppContext.user);
				AppContext.cleanAreaMsgInfo();
				AppContext.cleanUserOperateInfo();
				company.setText("未登录");
				avatar1.setImageResource(R.drawable.widget_dface_nor);
				basename.setText("未登录");
				tvMyLogin.setText("点击登录");
				System.out.println("unlogin:"+AppContext.user.getServerIp());
				((MainActivity) getActivity()).getTvBase().setText("");
				TToast.showToastShort("退出登录成功");
				dlg.dismiss();
			}
		});
		dlg.setNegativeButton("取消", null);
		dlg.show();
	}
	
	private void onClickCleanCache() {
		CommonDialog dialog = DialogHelper
				.getPinterestDialogCancelable(getActivity());
		dialog.setMessage("是否清空 "+caculateCacheSize()+" 缓存?");
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				clearAppCache(getActivity());
				dialog.dismiss();
			}
		});
		dialog.setNegativeButton("取消", null);
		dialog.show();
	}

	/**
	 * 清除app缓存
	 * 
	 * @param activity
	 */
	public static void clearAppCache(Activity activity) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					TToast.showToastShort("缓存清除成功");
				} else {
					TToast.showToastShort("缓存清除失败");
				}
			}
		};
		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				try {
					AppContext.clearAppCache();
					msg.what = 1;
				} catch (Exception e) {
					e.printStackTrace();
					msg.what = -1;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
	
    /**
     * 计算缓存的大小
     * @return 
     */
    private String caculateCacheSize() {
        long fileSize = 0;
        String cacheSize = "0KB";
        File filesDir = getActivity().getFilesDir();
        File cacheDir = getActivity().getCacheDir();

        fileSize += FileUtil.getDirSize(filesDir);
        fileSize += FileUtil.getDirSize(cacheDir);
        // 2.2版本才有将应用缓存转移到sd卡的功能
        if (MethodsCompat.isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            File externalCacheDir = MethodsCompat
                    .getExternalCacheDir(getActivity());
            fileSize += FileUtil.getDirSize(externalCacheDir);
        }
        if (fileSize > 0)
            cacheSize = FileUtil.formatFileSize(fileSize);
        return cacheSize;
    }
}